package com.moleq.mgpos.activities;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.moleq.adapter.ClerkReportAdapter;
import com.moleq.base.MoleQBaseActivity;
import com.moleq.base.MoleQBaseDialog;
import com.moleq.dialog.DateSettingSelectionDialog;
import com.moleq.dialog.InputDateInfoDialog;
import com.moleq.dialog.MessageDialog;
import com.moleq.dialog.MessageDialog.OnClickMessageListener;
import com.moleq.logic.PosPrinter;
import com.moleq.logic.ReportManager;
import com.moleq.models.GlobalInfo;
import com.moleq.models.PosSetting;
import com.moleq.models.Receipt;
import com.moleq.models.Users;
import com.moleq.mgpos.activities.R;
import com.moleq.service.ServiceManager;
import com.moleq.service.UsersService;
import com.moleq.util.MoleQUtil;

public class ClerkReportActivity extends MoleQBaseActivity {
	
	private Button btn_go,btn_print,btn_exit;
	private CheckBox cb_fixTotal,cb_functionKey;
	private EditText et_startDate,et_endDate;
	private ListView lv_clerk_list;
	private TextView tv_content;
	private String cashier;
	private MessageDialog mMessageDialog;
	private UsersService usersService;
	private Calendar cal = Calendar.getInstance();
	private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	private List<Users> userList = new ArrayList<Users>();
	private ClerkReportAdapter clerkReportAdapter;
	private DateSettingSelectionDialog mdssDialog;
	private InputDateInfoDialog ididDialog;
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_clerk_report);
		
		ControlFindId();
		btn_go.setOnClickListener(onClickListener);
		btn_print.setOnClickListener(onClickListener);
		btn_exit.setOnClickListener(onClickListener);
		et_startDate.setOnClickListener(onClickListener);
		et_endDate.setOnClickListener(onClickListener);
		lv_clerk_list.setOnItemClickListener(onItemClickListener);
		
		et_startDate.setText(sdf.format(cal.getTime()));
		et_endDate.setText(sdf.format(cal.getTime()));
		cashier = GlobalInfo.getInstance().cashier;
		usersService = ServiceManager.getInstance().mUsersService;
		if(usersService.CheckIsManager(cashier)){
			userList = usersService.getuserlist();
		}else{
			Users users = new Users();
			users.setUs_login_id(cashier);
			userList.add(users);
		}
		if(clerkReportAdapter == null){
			clerkReportAdapter = new ClerkReportAdapter(this, userList);
		}
		lv_clerk_list.setAdapter(clerkReportAdapter);
		
		mdssDialog = new DateSettingSelectionDialog(this);
		ididDialog = new InputDateInfoDialog(this, this);
		PosSetting item = ServiceManager.getInstance().mPosSettingService.Find();
		if(item == null){
			GlobalInfo.getInstance().calendar_type = false;
		}else{
			GlobalInfo.getInstance().calendar_type = item.isCalendarType();
		}
	}
	
	private void ControlFindId(){
		btn_go = (Button) this.findViewById(R.id.btn_go);
		btn_print = (Button) this.findViewById(R.id.btn_print);
		btn_exit = (Button) this.findViewById(R.id.btn_exit);
		
		cb_fixTotal = (CheckBox) this.findViewById(R.id.cb_fixTotal);
		cb_functionKey = (CheckBox) this.findViewById(R.id.cb_functionKey);
		
		et_startDate = (EditText) this.findViewById(R.id.et_startDate);
		et_endDate = (EditText) this.findViewById(R.id.et_endDate);
		
		lv_clerk_list = (ListView) this.findViewById(R.id.lv_clerk_list);
		
		tv_content = (TextView) this.findViewById(R.id.tv_content);
	}
	
	OnClickListener onClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.btn_go:
				String ls_content = "";
				tv_content.setText("");
				String sStartDate = MoleQUtil.fixDateTime2(
						String.valueOf(et_startDate.getText()), "yyyyMMdd",
						"yyyy-MM-dd");
				String sEndDate = MoleQUtil.fixDateTime2(
						String.valueOf(et_endDate.getText()), "yyyyMMdd",
						"yyyy-MM-dd");
				int iStartDate = Integer.valueOf(sStartDate);
				int iEndDate = Integer.valueOf(sEndDate);
				if(iStartDate > iEndDate) {
					Message("The end date cannot be earlier than start date.",
							mMessageDialog.MESSAGE_BOX_OK,
							mMessageDialog.ICON_INFO);
					return;
				}
				int days = MoleQUtil.getGapCount(et_startDate.getText().toString(), et_endDate.getText().toString());
				if (days > 90) {
					Message("Please enter the search period no longer than 90 days.",
							mMessageDialog.MESSAGE_BOX_OK,
							mMessageDialog.ICON_INFO);
					return;
				}
				
				String userId = userList.get(clerkReportAdapter.GetSelectedIndex()).getUs_login_id();
				Date StartDate = MoleQUtil.ChangeDate(String.valueOf(et_startDate.getText()));
				Date EndDate = MoleQUtil.ChangeDate(String.valueOf(et_endDate.getText()));
				Date[] dates = getDateArrays(StartDate,EndDate,Calendar.DAY_OF_YEAR);
				int kk = dates.length;
				ReportManager mCreateReport = new ReportManager();
				for (int i = 0; i < kk; i++) {
					SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd");
					String date = sdf2.format(dates[i]);
					if (cb_fixTotal.isChecked()) {
//						FixedTotalReport fixlReport = new FixedTotalReport(GlobalInfo.getInstance().ShareContext);
//						ls_content += fixlReport.CreateReport(date,userId);
						ls_content += mCreateReport.CreateFixedTotalReport(date, userId);
					}
					if (cb_functionKey.isChecked()) {
//						FreeFunctionReport freeFunReport = new FreeFunctionReport(GlobalInfo.getInstance().ShareContext);
//						ls_content += freeFunReport.CreateReport(date,userId);
						ls_content += mCreateReport.CreateFreeFunctionReport(date, userId);
					}
				}
				String result = "";
				if(ls_content.length() > 0){
					PosPrinter printer = new PosPrinter();
					List<Receipt> hearderlst = ServiceManager.getInstance().mReceiptService.FindALLHeader();
					if(hearderlst !=null){
					for(int k=0;k<hearderlst.size();k++){
						int align = 0,fontSize = 10 ; 
						
						if(hearderlst.get(k).getLarge().equals("L")){
							fontSize = PosPrinter.FONT_DOUBLE_SIZE;
						}else if(hearderlst.get(k).getLarge().equals("N")){
							fontSize = PosPrinter.FONT_SINGLE_SIZE;
						}
						
						if(hearderlst.get(k).getJustify().equals("L")){
							align = PosPrinter.LEFT;
						}else if(hearderlst.get(k).getJustify().equals("C")){
							align = PosPrinter.CENTER;
						}else if(hearderlst.get(k).getJustify().equals("R")){
							align = PosPrinter.RIGHT;
						}
						result += printer.toPrintContent(hearderlst.get(k).getMsg(),fontSize,align);
						
					}}
					int no = ServiceManager.getInstance().mPosSettingService.getAllPosSetting().get(0).getPs_station();
					result = MoleQUtil.parsePrintContent(result) + "\n Station " + no + "\n===============================================\n ";
					result += "Clerk # : " + userId + "\n";
				}
				ls_content = result + ls_content;
				tv_content.setText(ls_content);
				break;
			case R.id.btn_print:
				String context = tv_content.getText().toString();
				if(context.trim().equals("")) return;
				PosPrinter printer = new PosPrinter();
				if(!printer.isBusy()){
					printer.onConnect();
					printer.print(context);
					printer.cutPaper();
					printer.onDisconnect();
				}
				break;
			case R.id.btn_exit:
				Message("Do you want to exit ?",
						mMessageDialog.MESSAGE_BOX_YES_NO,
						mMessageDialog.ICON_INFO);
				break;
			case R.id.et_startDate:
				if (GlobalInfo.getInstance().calendar_type) {
					mdssDialog.show(R.id.et_startDate,et_startDate.getText().toString());
				}else{
					ididDialog.show(R.id.et_startDate,et_startDate.getText().toString());
				}
				break;
			case R.id.et_endDate:
				if (GlobalInfo.getInstance().calendar_type) {
					mdssDialog.show(R.id.et_endDate,et_endDate.getText().toString());
				}else{
					ididDialog.show(R.id.et_endDate,et_endDate.getText().toString());
				}
				break;
			default:
				break;
			}
		}
		
	};
	
	public OnItemClickListener onItemClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			// TODO Auto-generated method stub
			clerkReportAdapter.ScrollToRow(position);
		}
		
	};
	
	public void Message(String text, int type, int icon) {
		mMessageDialog = new MessageDialog(ClerkReportActivity.this);
		mMessageDialog.setStyle(type);
		mMessageDialog.setMessageIcon(icon);
		mMessageDialog.setMessage(text);
		mMessageDialog.setOnClickMessageListener(onClickMessageListener);
		mMessageDialog.show();
	}
	
	private OnClickMessageListener onClickMessageListener = new OnClickMessageListener() {

		public void onClickYes() {
			finish();
		}

		public void onClickNo() {
			mMessageDialog.dismiss();
		}

		public void onClickOK() {
			mMessageDialog.dismiss();
		}
	};
	
	public static Date[] getDateArrays(Date start, Date end, int calendarType) {
		ArrayList<Date> ret = new ArrayList<Date>();
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(start);
		Date tmpDate = calendar.getTime();
		long endTime = end.getTime();
		while (tmpDate.before(end) || tmpDate.getTime() == endTime) {
			ret.add(calendar.getTime());
			calendar.add(calendarType, 1);
			tmpDate = calendar.getTime();
		}

		Date[] dates = new Date[ret.size()];
		return ret.toArray(dates);
	}
	
	@Override
	public void onCloseWithReturn(Class<? extends MoleQBaseDialog> pramClass, int viewId, String parm) {
		super.onCloseWithReturn(pramClass, viewId, parm);
		
		switch (viewId) {
		case R.id.et_startDate:
			et_startDate.setText(parm);
			break;
		case R.id.et_endDate:
			et_endDate.setText(parm);
			break;
		default:
			break;
		}
	}
}
